﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 广州WMS_成品托号信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class GZWMSBarcodeInfoInfoController : ControllerBase
    {
        private readonly ILogger<GZWMSBarcodeInfoRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con_mes;
        public readonly string con_erp;
        public readonly string con_wms;
        public readonly string con_ddm;


        public GZWMSBarcodeInfoInfoController(ILogger<GZWMSBarcodeInfoRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
            con_mes = _configuration.GetConnectionString("GZ_MES_DbConnection");
            con_erp = _configuration.GetConnectionString("ERP_DbConnection");
            con_wms = _configuration.GetConnectionString("GZ_WMS_DbConnection");
            con_ddm = _configuration.GetConnectionString("DDM_DbConnection_ZH2");

        }

        /// <summary>
        /// 广州WMS_成品托号信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetBarcodeInfo([FromBody] GZWMSBarcodeInfoRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            GZWMSBarcodeInfoResponseDto re = new GZWMSBarcodeInfoResponseDto();
            string barcode_no = strparm.barcode_no;




            try
            {

                if (barcode_no.Trim() != "")
                {
                    strSql = new StringBuilder();
                    strSql.Append(@"select * from MESPanitStatus where CONTAINERNAME='"+ barcode_no + "' ");
                    DataTable dt_mes = DB.OracleQuery(strSql.ToString(), con_mes);
                    if (dt_mes.Rows.Count <= 0)
                    {
                        strMsg = "MES获取不到托盘<" + barcode_no + ">信息，请确认后再试！！！";
                    }
                    else
                    {
                        re.barcode_no = barcode_no;
                        re.material_amount = dt_mes.Rows[0]["QTY"].ToString();
                        re.work_order = dt_mes.Rows[0]["MFGORDERNAME"].ToString();
                        re.material_code = dt_mes.Rows[0]["PRODUCTNAME"].ToString();
                        re.customer_name = "";
                        re.material_name = dt_mes.Rows[0]["DESCRIPTION"].ToString();
                        re.material_power = dt_mes.Rows[0]["JKOFIPOWER"].ToString();
                        re.material_colour = dt_mes.Rows[0]["JKOCOLORNAME"].ToString();
                        re.material_grade = dt_mes.Rows[0]["JKOFIGRADE"].ToString();

                        strSql = new StringBuilder();
                        strSql.Append(@"SELECT L.organizationId, L.docno, L.lotAtt01, C.codedescr, L.sku,
       L.warehouseId, L.customerId, L.serialNo, L.expectedQty, L.lotAtt02,
       L.lotAtt03, L.lotAtt04, L.lotAtt05, L.lotAtt06, L.lotAtt07,
       L.lotAtt08, L.lotAtt09, L.lotAtt10, L.lotAtt11, L.lotAtt12,
       L.lotAtt13, L.lotAtt14, L.lotAtt15, L.lotAtt16, L.lotAtt17,
       L.lotAtt18, L.lotAtt19, L.lotAtt20, L.lotAtt21, L.lotAtt22,
       L.lotAtt23, L.lotAtt24, L.RQTY, L.QTY, L.CABINETNO1, L.UDF01,
       CASE
         WHEN L.UDF021 = '0060202' THEN
          '电池二车间'
         WHEN L.UDF021 = '0060201' THEN
          '电池一车间'
         else
          ''
       end AS UDF, L.UDF021, L.WORKSHOPNAME1,
       --D.STOCKFLAG1,
       L.SERIALNO1, L.STOCKFLAG1, L.addTime,
       --C.codeDescr AS CODE1,
       TO_CHAR(L.addTime, 'YYYY-MM-DD HH24:MI:SS') AS Time1
  FROM (
         
         SELECT D.ORGANIZATIONID, D.DOCNO, D.lotAtt01, D.sku, D.warehouseId,
                 D.customerId, D.serialNo, D.expectedQty, D.lotAtt02, D.lotAtt03,
                 D.lotAtt04, D.lotAtt05, D.lotAtt06, D.lotAtt07, D.lotAtt08,
                 D.lotAtt09, D.lotAtt10, D.lotAtt11, D.lotAtt12, D.lotAtt13,
                 D.lotAtt14, D.lotAtt15, D.lotAtt16, D.lotAtt17, D.lotAtt18,
                 D.lotAtt19, D.lotAtt20, D.lotAtt21, D.lotAtt22, D.lotAtt23,
                 D.lotAtt24, D.lotAtt25, D.lotAtt26, D.lotAtt27, D.lotAtt28,
                 D.lotAtt29, D.lotAtt30, D.lotAtt31, D.lotAtt32, D.lotAtt33,
                 D.lotAtt34, D.lotAtt35, D.lotAtt36, D.lotAtt37, D.lotAtt38,
                 D.lotAtt39, D.lotAtt40, D.lotAtt41, D.lotAtt42, D.lotAtt43,
                 D.lotAtt44, D.lotAtt45, D.CABINETNO1, D.UDF021, D.UDF01,
                 --D.STOCKFLAG1,
                 D.SERIALNO1, D.WORKSHOPNAME1,
                 case
                   when D.STOCKFLAG1 = 'W' OR
                        (D.STOCKFLAG1 = 'N' AND D.EDITTIME1 - D.ADDTIME < 0 AND
                        D.QTY > 0) OR
                        (D.STOCKFLAG1 = 'N' AND D.EDITTIME1 - D.ADDTIME < 0 AND
                        D.QTY = 0 AND D.EDITIME IS NULL) OR
                        (D.STOCKFLAG1 = 'N' AND D.RQTY = 0 AND
                        NVL(D.FLAG, 'N') <> 'Y' AND D.LINESTATUS = '99') then
                    '待收货'
                   WHEN D.STOCKFLAG1 = 'Y' THEN
                    '已在库'
                   when D.STOCKFLAG1 = 'N' AND D.RQTY = 0 AND
                        NVL(D.FLAG, 'N') = 'Y' AND D.LINESTATUS = '99' then
                    '取消收货'
                   else
                    '已发货'
                 end AS STOCKFLAG1, D.addTime, D.addTime1, D.QTY, D.RQTY,
                 D.editTime1
           FROM (
                   
                   SELECT S.*, S.CABINETNO AS CABINETNO1, S.UDF02 AS UDF021,
                           PB.WORKSHOPNAME AS WORKSHOPNAME1, A.SERIALNO AS SERIALNO1,
                           case
                             when A.STOCKFLAG is null then
                              'W'
                             when A.STOCKFLAG = 'Y' then
                              'Y'
                             else
                              'N'
                           end AS STOCKFLAG1, A.EDITTIME AS EDITTIME1,
                           A.ADDTIME AS ADDTIME1, A.QTY, A.RQTY, A.LINESTATUS,
                           A.FLAG
                     FROM CUS_MES_SERIALNO S
                     LEFT JOIN PLS_BAS_WORKSHOP PB
                       ON PB.ORGANIZATIONID = S.ORGANIZATIONID
                          AND PB.FACTORYID = S.CUSTOMERID
                          AND PB.workshopId = S.UDF02
                     LEFT JOIN (
                                
                                SELECT *
                                  FROM (
                                          
                                          SELECT ROW_NUMBER() OVER(PARTITION BY M.SERIALNO ORDER BY M.ADDTIME DESC NULLS LAST) mtime,
                                                  M.ORGANIZATIONID, M.WAREHOUSEID,
                                                  M.CUSTOMERID, M.SKU, M.SERIALNO,
                                                  M.STOCKFLAG, M.ADDTIME, M.EDITTIME,
                                                  M.QTY, DAD.RECEIVEDQTY_EACH AS RQTY,
                                                  DAD.LINESTATUS, DAH.EDISENDFLAG FLAG
                                            FROM DOC_ASN_SERIALNO M
                                            LEFT JOIN DOC_ASN_DETAILS DAD
                                              ON DAD.ORGANIZATIONID = M.ORGANIZATIONID
                                                 AND DAD.WAREHOUSEID = M.WAREHOUSEID
                                                 AND DAD.ASNNO = M.ASNNO
                                            LEFT JOIN DOC_ASN_HEADER DAH
                                              ON DAH.ORGANIZATIONID = DAD.ORGANIZATIONID
                                                 AND DAH.WAREHOUSEID = DAD.WAREHOUSEID
                                                 AND DAH.ASNNO = DAD.ASNNO
                                           WHERE M.ORGANIZATIONID = 'GOKIN'
                                                 AND M.WAREHOUSEID = 'GKH01FPW')
                                 WHERE mtime = 1) A
                       ON S.ORGANIZATIONID = A.ORGANIZATIONID
                          AND S.SKU = A.SKU
                          AND S.WAREHOUSEID = A.WAREHOUSEID
                          AND S.CUSTOMERID = A.CUSTOMERID
                          AND S.SERIALNO = A.SERIALNO) D) L
  LEFT JOIN BSM_CODE_ML C
    ON L.ORGANIZATIONID = C.ORGANIZATIONID
       AND C.codeType = 'ERP_WH'
       AND C.CODEID = L.lotAtt06
       AND C.languageId = 'zh_CN'
 WHERE 1 = 1 
 AND L.serialNo='" + barcode_no + "'  order by L.addTime desc ");
                        DataTable dt_wms = DB.OracleQuery(strSql.ToString(), con_wms);
                        if (dt_wms.Rows.Count > 0)
                        {
                            if (dt_wms.Rows[0]["STOCKFLAG1"].ToString() == "已在库")
                            {
                                if (dt_wms.Rows[0]["lotAtt14"].ToString() == "TP")
                                {
                                    re.material_state = "客户待检";
                                }
                                else if (dt_wms.Rows[0]["lotAtt14"].ToString() == "B")
                                {
                                    re.material_state = "在库免检";
                                }
                                else if (dt_wms.Rows[0]["lotAtt14"].ToString() == "Y")
                                {
                                    re.material_state = "客检NG";
                                }
                                else
                                {
                                    re.material_state = "客检OK";
                                }
                            }
                            else
                            {
                                re.material_state = dt_wms.Rows[0]["STOCKFLAG1"].ToString();
                            }

                        }
                        else
                        {
                            re.material_state = dt_mes.Rows[0]["PSTATUS"].ToString();
                        }

                        strSql = new StringBuilder();
                        strSql.Append(@"select nvl(ch.CUSTOMER_NAME,'广州高景太阳能科技有限公司') customer_name,we.WIP_ENTITY_NAME from 
apps.wip_discrete_jobs wdj,
apps.CUX_OM_CONTRACT_HEADERS_T ch,
apps.wip_entities we
where 1=1
and wdj.WIP_ENTITY_ID = we.WIP_ENTITY_ID
and wdj.ORGANIZATION_ID = we.ORGANIZATION_ID
and wdj.ATTRIBUTE4 = ch.CONTRACT_NAME(+)
and wdj.ORGANIZATION_ID = '241'
and ch.CONTRACT_OU(+) = '221'
AND NOT EXISTS --去除子工单
       (SELECT 1
                FROM apps.CUX_WIP_JOB_RELACTION_T CJR
               WHERE CJR.WIP_ENTITY_ID_CHILD = WDJ.WIP_ENTITY_ID) 
               AND we.WIP_ENTITY_NAME='" + dt_mes.Rows[0]["MFGORDERNAME"].ToString() + "' ");
                        DataTable dt_erp = DB.OracleQuery(strSql.ToString(), con_erp);
                        if (dt_erp.Rows.Count > 0)
                        {
                            re.customer_name = dt_erp.Rows[0]["customer_name"].ToString();
                        }

                    }
                }
               
              
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code =0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }


            return new JsonResult(re);
        }





    }
}
